package com.netease.research.controller;

import com.netease.research.common.Const;
import com.netease.research.common.ServerResponse;
import com.netease.research.pojo.User;
import com.netease.research.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class UserController {
    @Autowired
    private IUserService iUserService;

    @RequestMapping("login.do")
    @ResponseBody
    public ServerResponse<User> login(HttpSession session, HttpServletResponse response, String username, String password) throws IOException {

        ServerResponse<User> serverResponse = iUserService.login(username, password);
        if (serverResponse.isSuccess()) {
//            登录成功
            session.setAttribute(Const.CURRENT_USER, serverResponse.getData());
        } else {
//            登录失败
        }
        return serverResponse;
    }

    @RequestMapping("logout.do")
    @ResponseBody
    public ServerResponse logout(HttpSession session) {
        session.removeAttribute(Const.CURRENT_USER);
        return ServerResponse.createBySuccess();
    }

    @RequestMapping("get_user.do")
    @ResponseBody
    public ServerResponse<User> getUser(HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user != null) {
            user.setPassword("");
        }
        return ServerResponse.createBySuccess(user);
    }

}
